﻿//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2011 , JamSoft TECH, Ltd .
//-------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

// 本系统生成的类库
using DotNet.Business;
using DotNet.Utilities;

/// <remarks>
/// UserEdit
/// 用户编辑
/// 
/// 修改纪录
///	版本：1.0 2011.09.01 LiangMingMing  创建代码。 
/// <author>
///     <verison>1.0</verison>
///		<name>LiangMingMing</name>
///		<date>2011.09.01</date>
///		<description>用户注册</description>
/// </author> 
/// </remarks>
public partial class UserEdit : BasePage
{

    // **********************************************************************************************
    // *                                                                                            * 
    // *                             Public Variate    公共变量                                     *
    // *                                                                                            * 
    // **********************************************************************************************

    /// <summary>
    /// 编辑权限
    /// </summary>
    private bool PermissionEdit = false;
    /// <summary>
    /// 用户主键
    /// </summary>
    private string UserId
    {
        get
        {
            return this.txtID.Value;
        }
        set
        {
            this.txtID.Value = value;
        }
    }
    /// <summary>
    /// 用户详细地址
    /// </summary>
    private string UserAddressID
    {
        get
        {
            return this.txtUserAddressID.Value;
        }
        set
        {
            this.txtUserAddressID.Value = value;
        }
    }
    /// <summary>
    /// 返回地址
    /// </summary>
    public string ReturnPage
    {
        get
        {
            return this.txtReturnPage.Value;
        }
        set
        {
            this.txtReturnPage.Value = value;
        }
    }
    /// <summary>
    /// 多语言变量（添加到收藏夹）
    /// </summary>
    public string ToolbarFavorite = string.Empty;
    /// <summary>
    /// 多语言变量（显示隐藏左边菜单）
    /// </summary>
    public string ToolbarShowhideLeftFrame = string.Empty;
    /// <summary>
    /// 多语言变量（显示隐藏TOP页面）
    /// </summary>
    public string ToolbarShowhideTopFrame = string.Empty;
    /// <summary>
    /// 多语言变量（帮助中心）
    /// </summary>
    public string ToolbarHelp = string.Empty;
    /// <summary>
    /// 多语言-按钮（保存）
    /// </summary>
    public string ButtonConfirm = string.Empty;
    /// <summary>
    /// 多语言-按钮（返回）
    /// </summary>
    public string ButtonReturn = string.Empty;

    // **********************************************************************************************
    // *                                                                                            * 
    // *                             InitializeComponent  初始化                                    * 
    // *                                                                                            * 
    // **********************************************************************************************

    #region private void PageOnLoad() 加载窗体
    /// <summary>
    /// 加载窗体
    /// </summary>
    private void PageOnLoad()
    {
        // 读取参数
        this.GetParamter();
        // 绑定下拉框
        this.GetRoles();
        try
        {
            // 打开数据库连接
            this.UserCenterDbHelper.Open();
            // 显示内容
            this.ShowEntity();
        }
        catch (Exception exception)
        {
            // 记录异常信息
            LogException(exception);
            // 抛出错误
            throw exception;
        }
        finally
        {
            // 关闭数据库连接
            this.UserCenterDbHelper.Close();
        }
        // 设置焦点
        this.txtUserName.Focus();
    }
    #endregion

    // **********************************************************************************************
    // *                                                                                            * 
    // *                                       Method   操作方法                                    * 
    // *                                                                                            * 
    // **********************************************************************************************

    #region private void Localization() 多语言国际化加载
    /// <summary>
    /// 多语言国际化加载
    /// </summary>
    private void Localization()
    {
        // 多语言国际化加载
        ResourceManagerWrapper.Instance.LoadResources(Server.MapPath("../../../../Resource/Localization/"));
        // 获取语言信息
        this.GetLanguageResource(Utilities.GetCurrentLanguage(this.UserInfo));
    }
    #endregion

    #region private void GetLanguageResource(string languages) 获取语言
    /// <summary>
    /// 获取语言
    /// </summary>
    /// <param name="languages">语言类型</param>
    private void GetLanguageResource(string languages)
    {
        /// <以变量形式加载，刷新时会被刷掉所以得一直加载着>
        // 添加到收藏夹
        this.ToolbarFavorite = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.Favorite");
        // 显示隐藏左边菜单
        this.ToolbarShowhideLeftFrame = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.ShowhideLeftFrame");
        // 显示隐藏TOP页面
        this.ToolbarShowhideTopFrame = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.ShowhideTopFrame");
        // 帮助中心
        this.ToolbarHelp = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.Help");
        // 按钮-保存
        this.ButtonConfirm = ResourceManagerWrapper.Instance.Get(languages, "Button.Save");
        // 按钮-返回
        this.ButtonReturn = ResourceManagerWrapper.Instance.Get(languages, "Button.Return");
        /// <用的是控件，所以不怕被刷新>
        if (!Page.IsPostBack)
        {
            // 多语言(标题)
            this.Title = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx");
            // 多语言(用户修改)
            //this.ltlUserEdit.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlUserEidt");
            // 多语言（地址：）
            this.ltlAddress.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlAddress");
            // 多语言（生日：）
            this.ltlBirthday.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlBirthday");
            // 多语言（备注：）
            this.ltlDescription.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlDescription");
            // 多语言（电子邮件：）
            this.ltlEmail.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlEmail");
            // 多语言（传真：）
            this.ltlFax.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlFax");
            // 多语言（性别：）
            this.ltlGender.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlGender");
            // 多语言（手机:）
            this.ltlMobile.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlMobile");
            // 多语言（电话：）
            this.ltlPhone.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlPhone");
            // 多语言（邮政编码：）
            this.ltlPostCode.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlPostCode");
            // 多语言（QQ：）
            this.ltlQQ.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlQQ");
            // 多语言（姓名：）
            this.ltlRealname.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlRealname");
            // 多语言（用户管理-用户编辑）
            this.ltlTittle.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlTittle");
            // 多语言（用户名：）
            this.ltlUserName.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlUserName");
            // 多语言（默认角色：）
            this.ltlUserRole.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_ltlUserRole");
            // 有效
            this.cnkSelect.Text = ResourceManagerWrapper.Instance.Get(languages, "UserEdit.aspx_cnkSelect");
            // 下拉框请选择
            this.txtPleseSelect.Value = ResourceManagerWrapper.Instance.Get(languages, "DropDownList.Select");
            // ---- 提示信息 ------//
            // 记录未找到，可能已被其他人删除。
            this.hdfDelete.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG0005");
            // 提示信息:请输入用户名。
            this.hdfInputUserName.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50014");
            // 提示信息:修改成功。
            this.hdfSaveSuccess.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50024");
            // 提示信息:请选择用户角色
            this.hdfSelectRole.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50013");
        }
    }
    #endregion

    #region private void GetPermission() 获取权限
    /// <summary>
    /// 获取权限
    /// </summary>
    private void GetPermission()
    {
        // 获取编辑权限
        this.PermissionEdit = this.IsAuthorized("UserAdmin.Edit");
        // 没有权限
        if (!this.PermissionEdit)
        {
            // 跳转没有权限页面
            Response.Redirect(Utilities.AccessDenyPage);
        }
    }
    #endregion

    #region private void ShowEntity() 显示用户数据
    /// <summary>
    /// 显示用户数据
    /// </summary>
    private void ShowEntity()
    {
        // 实例化用户业务逻辑操作类
        BaseUserManager userManager = new BaseUserManager(this.UserCenterDbHelper);
        // 实例化获取用户实体
        BaseUserEntity userEntity = userManager.GetEntity(this.UserId);
        /// 在页面上显示
        // 用户名
        this.txtUserName.Text = userEntity.UserName;
        // 姓名
        this.txtRealname.Text = userEntity.RealName;
        // 角色
        this.ddlUserRole.SelectedValue = userEntity.RoleId == null ? string.Empty : userEntity.RoleId.ToString();
        // 生日
        this.txtBirthday.Text = userEntity.Birthday;
        // 备注
        this.txtDescription.Text = userEntity.Description;
        // 电子邮件
        this.txtEmail.Text = userEntity.Email;
        // 手机号
        this.txtMobile.Text = userEntity.Mobile;
        // QQ
        this.txtQQ.Text = userEntity.OICQ;
        // 性别
        this.rdblGender.SelectedValue = userEntity.Gender;
        // 有效 
        this.cnkSelect.Checked = userEntity.Enabled == 1;
        //  显示用户详细信息
        this.ShowUserAddress(userEntity.UserAddressId);
        // 判断数据是否被其他人删除
        if ((userEntity.Id == null) || (userEntity.Id == 0))
        {
            //this.lblPrompt.Text = AppMessage.MSG0005;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script>alert('" + this.hdfDelete.Value + "');</script>");
        }
    }
    #endregion

    #region private void ShowUserAddress(string id) 显示用户详细地址
    /// <summary>
    /// 显示用户详细地址
    /// </summary>
    /// <param name="id">地址主键</param>
    private void ShowUserAddress(string id)
    {
        // 判断地址主键是否为空
        if (!string.IsNullOrEmpty(id))
        {
            // 实列化用户地址操作类
            BaseUserAddressManager userAddressManager = new BaseUserAddressManager(this.UserCenterDbHelper);
            // 实列化用户地址实体
            BaseUserAddressEntity userAddressEntity = userAddressManager.GetEntity(id);
            // 地址
            this.txtAddress.Text = userAddressEntity.Address;
            // 传真
            this.txtFax.Text = userAddressEntity.Fax;
            // 邮编
            this.txtPostCode.Text = userAddressEntity.PostCode;
            // 电话
            this.txtPhone.Text = userAddressEntity.PostCode;
        }
    }
    #endregion

    #region private BaseUserEntity GetUserEntity() 获取用户实体
    /// <summary>
    /// 获取用户实体
    /// </summary>
    /// <returns></returns>
    private BaseUserEntity GetUserEntity()
    {
        // 实例化用户业务逻辑操作类
        BaseUserManager userManager = new BaseUserManager(this.UserCenterDbHelper);
        // 实例化获取用户实体
        BaseUserEntity userEntity = userManager.GetEntity(this.UserId);
        // 用户名
        userEntity.UserName = this.txtUserName.Text;
        // 姓名
        userEntity.RealName = this.txtRealname.Text;
        // 用户角色
        if (this.ddlUserRole.SelectedValue != null)
        {
            // 获取用户角色主键
            userEntity.RoleId = int.Parse(this.ddlUserRole.SelectedValue);
        }
        // 生日
        userEntity.Birthday = this.txtBirthday.Text;
        // 备注
        userEntity.Description = this.txtDescription.Text;
        // 电子邮件
        userEntity.Email = this.txtEmail.Text;
        // 手机号
        userEntity.Mobile = this.txtMobile.Text;
        // QQ
        userEntity.OICQ = this.txtQQ.Text;
        // 性别
        userEntity.Gender = this.rdblGender.SelectedValue;
        // 有效 
        userEntity.Enabled = this.cnkSelect.Checked ? 1 : 0;
        return userEntity;
    }
    #endregion

    #region private BaseUserAddressEntity GetUserAddressEntity(string id) 获取用户地址详细信息
    /// <summary>
    /// 获取用户地址详细信息
    /// </summary>
    /// <param name="id">地址主键</param>
    /// <returns></returns>
    private BaseUserAddressEntity GetUserAddressEntity(string id)
    {
        // 实例化用户地址详细信息操作类
        BaseUserAddressEntity userAddressEntity = new BaseUserAddressEntity();
        // 判断地址主键是否为空
        if (!string.IsNullOrEmpty(id))
        {
            // 实列化用户地址操作类
            BaseUserAddressManager userAddressManager = new BaseUserAddressManager(this.UserCenterDbHelper);
            userAddressEntity = userAddressManager.GetEntity(id);
        }
        // 地址
        userAddressEntity.Address = this.txtAddress.Text;
        // 传真
        userAddressEntity.Fax = this.txtFax.Text;
        // 邮编
        userAddressEntity.PostCode = this.txtPostCode.Text;
        // 电话
        userAddressEntity.Phone = this.txtPhone.Text;
        //userAddressEntity.DeletionStateCode = 0;
        //userAddressEntity.Enabled = 1;   
        // 返回结果
        return userAddressEntity;
    }
    #endregion

    //#region private bool SaveEntity() 保存
    ///// <summary>
    ///// 保存
    ///// </summary>
    ///// <returns>成功</returns>
    //private void SaveEntity()
    //{
    //    try
    //    {
    //        // 状态
    //        string statusCode = string.Empty;
    //        // 返回信息
    //        string statusMessage = string.Empty;
    //        // 打开数据库连接
    //        this.UserCenterDbHelper.Open();
    //        // 实例化用业务逻辑操作类
    //        BaseUserManager userManager = new BaseUserManager(this.UserCenterDbHelper);
    //        // 获取用户实体
    //        BaseUserEntity userEntity = this.GetUserEntity();
    //        // 更新数据库
    //        userManager.Update(userEntity, out statusCode);
    //        // 获取用户地址详细信息实体
    //        BaseUserAddressEntity userAddressEntity = this.GetUserAddressEntity(userEntity.UserAddressId);
    //        // 实例化用户地址详细业务逻辑操作类
    //        BaseUserAddressManager userAddressManager = new BaseUserAddressManager(this.UserCenterDbHelper);
    //        if ((userAddressEntity.Id != null) && (userEntity.UserAddressId != null))
    //        {
    //            userAddressManager.UpdateEntity(userAddressEntity);
    //        }
    //        else
    //        {
    //            string id = userAddressManager.Add(userAddressEntity, true);
    //            userManager.SetProperty(userEntity.Id, BaseUserEntity.FieldUserAddressId, id);
    //        }
    //        if (statusCode == StatusCode.OKUpdate.ToString())
    //        {
    //            if (BaseSystemInfo.ShowInformation)
    //            {
    //                // 保存成功，进行提示
    //                //this.lblPrompt.Text = "提示信息：保存成功。";
    //                if (Utilities.IsPageRedirect)
    //                {
    //                    Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script>alert('" + this.hdfSaveSuccess.Value + "');window.location.href='" + this.ReturnPage + "'</script>");
    //                }
    //                else
    //                {
    //                    Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script>alert('" + this.hdfSaveSuccess.Value + "');</script>");
    //                }
    //            }
    //        }
    //        else
    //        {
    //            //this.lblPrompt.Text = AppMessage.MSG0000;
    //            string checkInput = "<script>document.getElementById('" + this.txtUserName.ClientID + "').focus();</script>";
    //            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        this.LogException(ex);
    //        throw ex;
    //    }
    //    finally
    //    {
    //        // 关闭数据库连接
    //        this.UserCenterDbHelper.Close();
    //    }
    //}
    //#endregion

    #region private bool SaveEntity() 保存
    /// <summary>
    /// 保存
    /// </summary>
    /// <returns>成功</returns>
    private void SaveEntity()
    {
        try
        {
            // 状态
            string statusCode = string.Empty;
            // 信息
            string statusMessage = string.Empty;
            string role = string.Empty;
            if (this.ddlUserRole.SelectedValue != null)
            {
                role = this.ddlUserRole.SelectedValue.ToString();
            }
            // 更新到数据库
            BaseUserEntity userEntity = new BaseUserEntity();
            userEntity = this.GetUserEntity();
            // DotNetService.Instance.UserService.UpdateUser(this.UserInfo, this.UserId, this.txtUserName.Text, this.txtRealname.Text, string.Empty, role, string.Empty, this.cnkSelect.Checked, out statusCode, out statusMessage);
            DotNetService dotNetService = new DotNetService();
            dotNetService.UserService.UpdateUser(this.UserInfo, userEntity, out statusCode, out statusMessage);
            if (statusCode == StatusCode.OKUpdate.ToString())
            {
                if (BaseSystemInfo.ShowInformation)
                {
                    // 保存成功，进行提示
                    //this.lblPrompt.Text = "提示信息：保存成功。";
                    if (Utilities.IsPageRedirect)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script>alert('" + this.hdfSaveSuccess.Value + "');window.location.href='" + this.ReturnPage + "'</script>");
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script>alert('" + this.hdfSaveSuccess.Value + "');</script>");
                    }
                }
            }
            else
            {
                //this.lblPrompt.Text = AppMessage.MSG0000;
                string checkInput = "<script>document.getElementById('" + this.txtUserName.ClientID + "').focus();</script>";
                ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            }
        }
        catch (Exception ex)
        {
            this.LogException(ex);
            throw ex;
        }
    }
    #endregion

    #region private void GetParamter() 读取参数
    /// <summary>
    /// 读取参数
    /// </summary>
    private void GetParamter()
    {
        // 获取用户主键
        if (Page.Request["ID"] != null)
        {
            this.UserId = Page.Request["ID"].ToString();
        }
        else
        {
            this.Page.Response.Redirect(Utilities.DefaultPage);
        }
        // 获取返回地址
        if (Page.Request["ReturnPage"] != null)
        {
            this.txtReturnPage.Value = Page.Request["ReturnPage"].ToString();
        }
    }
    #endregion

    #region private bool CheckInput() 检查页面输入
    /// <summary>
    /// 检查页面输入
    /// </summary>
    /// <returns>是否正确</returns>
    private bool CheckInput()
    {
        bool returnValue = true;
        string checkInput = string.Empty;
        if (this.txtUserName.Text.Length == 0)
        {
            checkInput = "<script>alert('" + this.hdfInputUserName.Value + "'); document.getElementById('" + this.txtUserName.ClientID + "').focus();</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            return false;
        }
        if (this.ddlUserRole.SelectedIndex < 1)
        {
            checkInput = "<script>alert('" + this.hdfSelectRole.Value + "');document.getElementById('" + this.ddlUserRole.ClientID + "').focus();</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            return false;
        }
        return returnValue;
    }
    #endregion

    #region private void GetRoles() 获取角色列表
    /// <summary>
    /// 获取角色列表
    /// </summary>
    private void GetRoles()
    {
        DotNetService dotNetService = new DotNetService();
        // 绑定类型数据
        DataTable dataTable = dotNetService.RoleService.GetDataTable(this.UserInfo);
        this.ddlUserRole.DataTextField = BaseRoleEntity.FieldRealName;
        this.ddlUserRole.DataValueField = BaseRoleEntity.FieldId;
        this.ddlUserRole.DataSource = dataTable.DefaultView;
        this.ddlUserRole.DataBind();
        // 插入空列
        this.ddlUserRole.Items.Insert(0, new ListItem(this.txtPleseSelect.Value, string.Empty));
    }
    #endregion

    // **********************************************************************************************
    // *                                                                                            * 
    // *                                       EventArgs    事件方法                                * 
    // *                                                                                            * 
    // ********************************************************************************************** 

    #region protected void Page_Load(object sender, EventArgs e) 页面初次加载的动作
    /// <summary>
    /// 页面初次加载的动作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        // 加载多语言
        this.Localization();
        // 获取权限
        //this.GetPermission();
        // 是否回发
        if (!this.IsPostBack)
        {
            // 加载窗体
            this.PageOnLoad();
        }
    }
    #endregion

    #region protected void btnSave_Click(object sender, EventArgs e) 保存
    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // 检查页面输入
        if (this.CheckInput())
        {
            // 保存
            this.SaveEntity();
        }
    }
    #endregion

    #region protected void btnReturn_Click(object sender, EventArgs e) 返回
    /// <summary>
    /// 返回
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        // 判断是否带加载效果
        if (Utilities.IsLoading)
            // 转向返回页面（带加载效果）
            Page.Response.Redirect(Utilities.LoadingPageUrl +Server.UrlEncode(this.ReturnPage));
        else
            // 转向返回页面
            Page.Response.Redirect(this.ReturnPage);
    }
    #endregion
}